package memberdao

import (
	"fmt"
	"gorm.io/gorm"
	"strings"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/helper/resphelper/memberresp"
	"yundian/internel/app/models/fddextsignuser"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
)

// GetAdminMemberList 获取会员列表
func (d *MemberDao) GetAdminMemberList(param *request.GetMembersListReq) *dingo.ErrorWrap {
	var lst []request.GetMembersListRes

	db := global.Orm.Table("members")

	if param.Phone != "" {
		db.Where("phone like ?", fmt.Sprint("%", param.Phone, "%"))
	}

	db.Group("phone").Limit(20).Find(&lst)
	return dingo.ErrorIf(db.Error, lst)
}

// UpdateMemberStatus 更新会员状态
func (d *MemberDao) UpdateMemberStatus(id int, status int8) *dingo.ErrorWrap {
	sql := "update members set state = ? where id = ?"
	db := global.Orm.Exec(sql, status, id)
	return dingo.ErrorIf(db.Error, true)
}

// GetMemberList 获取会员列表
func (d *MemberDao) GetMemberList(param *request.MemberListReq) *dingo.ErrorWrap {

	var (
		lst    []memberresp.MembersList
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)

	db := global.Orm.Table("members").
		Select("REPLACE(phone, SUBSTR(phone,4,4), '****') as phone," +
			"REPLACE(nick_name, SUBSTR(nick_name,4,4), '****') as nick_name,state,reg_from,id,xcx_openid," +
			"wx_openid,uuid,create_at,update_at")

	if param.NickName != "" { db.Where("nick_name like ?", fmt.Sprint("%", param.NickName, "%")) }
	if param.Openid != "" { db.Where("xcx_openid = ?", param.Openid) }
	if param.Phone != "" { db.Where("phone = ?", param.Phone) }
	if param.State > 0 { db.Where("state = ?", param.State) }
	if param.RegFrom != "" { db.Where("reg_from = ?", param.RegFrom) }

	// 时间查询
	if param.BeginTime != "" {
		beginTime := strings.Split(param.BeginTime, ",")
		db.Where("create_at >= ? and create_at <= ?", beginTime[0], beginTime[1])
	}

	// 排序
	if param.SortField != "" && param.SortOrder == "ascend" {
		db.Order(fmt.Sprintf("%s asc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField != "" && param.SortOrder == "descend" {
		db.Order(fmt.Sprintf("%s desc", utils.String(param.SortField).SnakeCase()))
	}
	if param.SortField == "" { db.Order("id desc") }

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}

// GetMemberInfoByOpenid 获取用户信息
func (d *MemberDao) GetMemberInfoByOpenid(openid string) *dingo.ErrorWrap {
	m := membermodel.New()
	sql := "select * from members where xcx_openid = ? limit 1"
	db := global.Orm.Raw(sql, openid).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *MemberDao) GetMemberInfoByOpenidAndAppId(openid, appId string) *dingo.ErrorWrap {
	m := membermodel.New()
	sql := "select * from members where xcx_openid = ? and app_id = ? limit 1"
	db := global.Orm.Debug().Raw(sql, openid, appId).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// GetMemberInfoByOpenidOrUnionid 获取会员详情
func (d *MemberDao) GetMemberInfoByOpenidOrUnionid(openid, unionid string) *dingo.ErrorWrap {
	m := membermodel.New()
	db := global.Orm.Table("members")
	if unionid != "" {
		db.Where("unionid = ?", unionid)
	} else {
		db.Where("xcx_openid = ?", openid)
	}
	db.Limit(1).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// InsertMember 新增用户
func (d *MemberDao) InsertMember(m *membermodel.MembersModel) *dingo.ErrorWrap {
	db := global.Orm.Table("members").Create(&m)
	return dingo.ErrorIf(db.Error, m)
}

// GetMemberInfoById 获取用户信息
func (d *MemberDao) GetMemberInfoById(id int) *dingo.ErrorWrap {
	m := membermodel.New()
	sql := "select * from members where id = ? limit 1"
	db := global.Orm.Raw(sql, id).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *MemberDao) GetUserInfoByOpenid(openid string) *dingo.ErrorWrap {
	m := users.UserModel{}
	sql := "select * from users where zfb_openid = ? limit 1"
	db := global.Orm.Raw(sql, openid).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// UpdateMemberInfoById 更新用户信息
func (d *MemberDao) UpdateMemberInfoById(m *membermodel.MembersModel) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("members").Where("id = ?", m.ID).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

//判断是否注册过法大大
func (d *MemberDao) GetFddExtSignUserByOpenId(userId int) *dingo.ErrorWrap {
	m := users.UserModel{}
	db := global.Orm.Table("users").Where("id = ?", userId).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

//判断是否注册过法大大
func (d *MemberDao) GetFddExtSignUserRows(openId string) (*dingo.ErrorWrap, int64) {
	m := fddextsignuser.FddExtSignUser{}
	db := global.Orm.Table("fdd_ext_sign_user").Where("openid = ?", openId).Find(&m)
	return dingo.ErrorIf(db.Error, m), db.RowsAffected
}

//查询是否实名认证
func (d *MemberDao) GetExtSignInfo(userId int) *dingo.ErrorWrap {
	m := fddextsignuser.FddExtSignUser{}
	db := global.Orm.Debug().Table("fdd_ext_sign_user").Where("user_id = ?", userId).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

//使用合同编号查询用户
func (d *MemberDao) GetUserInfoByContractId(contractId string) *dingo.ErrorWrap {
	m := fddextsignuser.FddExtSignUser{}
	db := global.Orm.Table("fdd_ext_sign_user").Where("contract_id = ?", contractId).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

//使用Fdd客户编号查询用户 customer_id
func (d *MemberDao) GetUserInfoByCustomerId(customerId string) *dingo.ErrorWrap {
	m := fddextsignuser.FddExtSignUser{}
	db := global.Orm.Table("fdd_ext_sign_user").Where("customer_id = ?", customerId).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *MemberDao) UpdateByContractId(m *fddextsignuser.FddExtSignUser) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("fdd_ext_sign_user").Select("is_signed,sign_contract_url").Where("contract_id= ?", m.ContractId).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *MemberDao) InsertFddExtSignUser(m *fddextsignuser.FddExtSignUser) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("fdd_ext_sign_user").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *MemberDao) UpdateFddUserTransactionNo(m *fddextsignuser.FddExtSignUser) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("fdd_ext_sign_user").Select("transaction_no").Where("user_id= ?", m.UserId).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *MemberDao) UpdateFddUserIsExt(m *fddextsignuser.FddExtSignUser) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("fdd_ext_sign_user").Select("is_ext,contract_id").Where("user_id= ?", m.UserId).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *MemberDao) UpdateIdIsExtByCustomer(m *fddextsignuser.FddExtSignUser) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("fdd_ext_sign_user").Select("is_ext").Where("customer_id= ?", m.CustomerId).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *MemberDao) UpdateIsSignedAt(m *fddextsignuser.FddExtSignUser) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("fdd_ext_sign_user").Select("signed_at").Where("id = ?", m.Id).Model(&m).Updates(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *MemberDao) GetFddExtSignUserInfo(userId int) *dingo.ErrorWrap {
	m := fddextsignuser.FddExtSignUser{}
	db := global.Orm.Table("fdd_ext_sign_user").Where("user_id = ?", userId).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

func (d *MemberDao) GetUserInfoWithMemberInfo(id int) *dingo.ErrorWrap {
	m := &users.UserModel{}
	sql := "select u.* from members m LEFT JOIN users u ON m.phone = u.phone where m.id = ? limit 1"
	db := global.Orm.Raw(sql, id).Find(m)
	return dingo.ErrorIf(db.Error, m)
}



// GetMemberInfoById 查询会员信息
func (d *MemberDao) GetMemberInfoByMemberId(dbOrm *gorm.DB, id int) *dingo.ErrorWrap {
	m := membermodel.New()
	sql := "select * from members where id = ? limit 1"
	db := dbOrm.Raw(sql, id).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}

// UpdateBalanceAmount 更新帐户金额
func (d *MemberDao) UpdateBalanceAmount(dbOrm *gorm.DB, param *membermodel.MemberPclBalance) *dingo.ErrorWrap {
	memberData := d.GetMemberInfoByMemberId(dbOrm, param.MemberId)
	if memberData.Err != nil {
		return dingo.ErrorIf(memberData.Err)
	}
	memberInfo := memberData.Unwrap().(*membermodel.MembersModel)
	param.OldBalance = int(memberInfo.Balance)
	param.NewBalance = int(memberInfo.Balance) + param.Amount
	if db := dbOrm.Table("member_pcl_balance").Create(&param); db.Error != nil {
		return dingo.ErrorIf(db.Error)
	}

	updateSql := `UPDATE members SET balance=balance+? WHERE id=?`
	db := dbOrm.Exec(updateSql, param.Amount, param.MemberId)
	return dingo.ErrorIf(db.Error)
}

func (d *MemberDao) GetMemberInfoByUuId(uuid string) *dingo.ErrorWrap {
	m := membermodel.New()
	sql := "select * from members where uuid = ? limit 1"
	db := global.Orm.Raw(sql, uuid).Find(&m)
	return dingo.ErrorIf(db.Error, m)
}
